from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.utils import text
from django.views.decorators.csrf import csrf_exempt
# from django.contrib.auth.models import AbstractUser
import json
import time

from haystack.views import SearchView
from rest_framework import request
from rest_framework.views import APIView

from .models import items
from orders.models import orders
from users import models
# Create your views here.
import json

from .serializers import ItemsSerializers, ItemsPageNumberPagination
@csrf_exempt
class MySearchView(SearchView):
  @csrf_exempt
  def create_response(self):
    context = super().get_context()
    keyword = self.request.GET.get('q', None)  # 关键子为q
    if not keyword:
      return JsonResponse({'message': '没有相关信息'})
    # context = self.get_context()
    data_list = []

    # return HttpResponse(context['page'].object_list)
    for i in context['page'].object_list:
      data_dict = {}
      data_dict['itemsPublisher'] = i.object.itemsPublisher.username
      data_dict['itemsID'] = str(i.object.itemsID).replace("-","")
      data_dict['itemsName'] = i.object.itemsName
      data_dict['remark'] = i.object.remark

      data_dict['itemsNumber'] = i.object.itemsNumber
      data_dict['itemsMaxNum'] = i.object.itemsMaxNum
      data_dict['itemsPicture'] = i.object.itemsPicture
      data_dict['itemsPrice'] = i.object.itemsPrice
      print(data_dict.values())
      data_list.append(data_dict)

    # print(context['page'].object_list)
    #
    return JsonResponse(data_list, safe=False)




@csrf_exempt
def optItems(request):
  if 'username' not in request.session:
    return JsonResponse({'code': 101, 'msg': '用户未登录！', 'data': ''})

  if request.method == 'GET':
    request = APIView().initialize_request(request)
    typecode = request.GET.get('typecode')
    allitems = items.objects.all()
    # print(typecode)
    if typecode == '1':
      allitems = allitems.filter(itemsType = '公共资源')
    elif typecode == '2':
      allitems = allitems.filter(itemsType='个人资源')
    elif typecode == '3':
      allitems = allitems.filter(itemsType='个人能力')
    # return HttpResponse(len(allitems))
    if len(allitems) == 0:
      return JsonResponse({'code': 101, 'msg': '未发布过此类资源', 'data': ''})
    pg = ItemsPageNumberPagination()
    page_roles = pg.paginate_queryset(queryset=allitems, request=request, view=None)
    ser = ItemsSerializers(instance=page_roles, many=True)
    for i in range(len(ser.data)):
      ser.data[i]['itemsID'] = ser.data[i]['itemsID'].replace("-","")
    response = {'code': 200, 'msg': '获取成功并返回页面', 'count': 1000000, 'data': ser.data}
    return JsonResponse(response)







@csrf_exempt
def makeOrder(request,self):
  if 'username' not in request.session:
    return JsonResponse({'code': 101, 'msg': '用户未登录！', 'data': ''})
  if request.method == 'POST':
    data = json.loads(request.body.decode('utf-8'))
    buyerNumber = request.session.get('username')
    itemsID = data['itemsID']
    item = items.objects.filter(itemsID = itemsID)
    if len(item) == 0:
      return JsonResponse({'code':101, 'msg':'不存在该物品', 'data':''})
    item = items.objects.get(itemsID = itemsID)


    buyNum = data['buyNum'] # 如果不是周期性的买多少
    nowNum = item.itemsNumber
    if buyNum > nowNum:
      return JsonResponse({'code':101, 'msg':'物品在某一天的数量不够', 'data':''})
    nowNum = nowNum - buyNum
    item.itemsNumber = nowNum
    # return HttpResponse(nowNum)
    pr = item.itemsPrice*buyNum

    neworder = orders(orderItemsName = item.itemsName, orderDate = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
    if item.itemsType == '公共资源':
      neworder.orderStatus = '待审批' # 等到付款成功变成 '已完成
    else:
      neworder.orderStatus = '待付款' # 等到审核完毕变成 2
    neworder.orderPrice = pr
    neworder.orderItemsPrice = item.itemsPrice
    neworder.orderItemsID = item.itemsID
    buyer = models.user.objects.get(username = buyerNumber)
    neworder.buyer = buyer
    neworder.orderItemsNum = buyNum
    seller = item.itemsPublisher
    neworder.seller = seller
    neworder.orderItemsPicture = item.itemsPicture
    neworder.save()
    orderID = str(neworder.orderID).replace("-","")
    item.save()
    return JsonResponse({'code':200, 'msg':'订单下成功', 'data':orderID})

  if request.method == 'GET' :
    if request.method == 'GET':
      data = request.GET
      itemsID = data['itemsID']
      thisitem = items.objects.all().filter(itemsID=itemsID)
      if len(thisitem) == 0:
        return JsonResponse({'code': 101, 'msg': '没有此物品', 'data': ''})
      # response = {}
      # response['code'] = 200
      # response['msg'] = '成功'
      # item = thisitem.values('itemsID', 'itemsName', 'itemsPrice', 'itemsStartTime', 'itemsLastTime', 'itemsNumber',
      #                        'itemsMaxNum', 'remark')
      # list_dict = item.values()
      # response['data'] = json.dumps(list_dict,ensure_ascii=False)
      # response = json.dumps(response)
      # return HttpResponse(response)
      thisitem = items.objects.all().filter(itemsID=itemsID)
      serializer = ItemsSerializers(instance=thisitem, many=True)
      resdata = serializer.data[0]
      resdata['itemsID'] = resdata['itemsID'].replace("-","")
      resdata['itemsPublisher']
      res = {'code': 200, 'msg': '成功', 'data': resdata}
      return JsonResponse(res)
    